import {createRouter, createWebHistory} from 'vue-router'
import VueCookie from 'vue-cookie'
import superRoutes from './SuperRoutes'
import userRoutes from './userRoutes'
import loginRoutes from './LoginRoutes'
import MerchantRoutes from "@/router/MerchantRoutes.js";
import {ElMessageBox, ElMessage} from "element-plus";
import {fetchUser, getUser} from "@/components/userInfo.js"
import {watchEffect} from "vue";


const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'default',
            redirect: '/user/home',
        },
        {
            path: '/test',
            name: 'Test',
            component: () => import('@/views/test/test.vue')
        },
        ...loginRoutes,
        ...userRoutes,
        ...superRoutes,
        ...MerchantRoutes

    ]
})
const whiteList = [
    '/login',
    '/register',
    '/forget',
    '/user/home',
    '/user/merchant',
    '/user/script',
    '/user/search',
    '/user/merchant/detail',
    '/user/script/detail'
]
const toLogin = [
    '/login',
    '/register',
    '/forget'
]

const supRouter = /^\/sup(\/.*)?$/
const merRouter = /^\/mer(\/.*)?$/

router.beforeEach(async (to, from, next) => {
    // 判断用户是否登录
    const token = VueCookie.get('sessionId');
    await fetchUser()

    // 判断用户角色
    let userRole = ''
    if (getUser.value !== null) {
        if (getUser.value.role === 0) {
            userRole = '普通用户'
        } else if (getUser.value.role === 1) {
            userRole = '商家'
        } else if (getUser.value.role === 2) {
            userRole = '超级管理员'
        }
    } else {
        userRole = '游客'
    }

    console.log("当前角色为：" + userRole);



    if (toLogin.includes(to.fullPath) && token) {
        console.log('已经登录，重定向到首页');
        next('/user/home'); // 如果已经登录，则重定向到首页
        return;
    }
    if (supRouter.test(to.fullPath) && getUser.value.role !== 2) {
        ElMessage.warning('您没有访问该页面的权限');
        next('/user/home'); // 如果已经登录，则重定向到首页
        return;
    }
    if (merRouter.test(to.fullPath) && getUser.value.role !== 1) {
        ElMessage.warning('您没有访问该页面的权限');
        next('/user/home'); // 如果已经登录，则重定向到首页
        return;
    }
    if (whiteList.includes(to.fullPath) || token) {
        console.log('当前页面：' +to.fullPath + '，允许访问');
        next(); // 如果在白名单中或者已经登录，则直接进入目标页面
        return;
    }
    try {
        await ElMessageBox.confirm('您还未登录，请先登录！', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        next('/login'); // 跳转到登录页面
    } catch (error) {
        next(false); // 取消导航
    }
});


export default router